﻿#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <unordered_set>
using namespace std;

class Solution
{
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
public:
    // 1926. 迷宫中离入口最近的出口
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance)
    {
        int m, n;
        bool vis[110][110];
        memset(vis, 0, sizeof vis);
        queue<pair<int, int>> q;
        q.push({ entrance[0], entrance[1] });
        m = maze.size(), n = maze[0].size();
        vis[entrance[0]][entrance[1]] = true;

        int ret = 0;
        while (q.size())
        {
            ret++;
            int sz = q.size();
            for (int i = 0; i < sz; i++)
            {
                pair<int, int> p = q.front();
                q.pop();
                int a = p.first, b = p.second;

                for (int k = 0; k < 4; k++)
                {
                    int x = a + dx[k], y = b + dy[k];
                    if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && maze[x][y] != '+')
                    {
                        vis[x][y] = true;
                        if (x == 0 || y == 0 || x == m - 1 || y == n - 1)
                            return ret;
                        q.push({ x,y });
                    }
                }
            }
        }
        return -1;
    }

    // 433. 最小基因变化
    int minMutation(string startGene, string endGene, vector<string>& bank)
    {
        unordered_set<string> vis;
        unordered_set<string> hash(bank.begin(), bank.end());
        string change = "ACGT";

        if (startGene == endGene)
            return 0;
        if (!hash.count(endGene))
            return -1;

        queue<string> q;
        q.push(startGene);
        vis.insert(startGene);

        int ret = 0;
        while (q.size())
        {
            ret++;
            int sz = q.size();
            while (sz--)
            {
                string t = q.front();
                q.pop();

                for (int i = 0; i < 8; i++)
                {
                    string tmp = t;
                    for (int j = 0; j < 4; j++)
                    {
                        tmp[i] = change[j];
                        if (hash.count(tmp) && !vis.count(tmp))
                        {
                            if (tmp == endGene)
                                return ret;
                            q.push(tmp);
                            vis.insert(tmp);
                        }
                    }
                }
            }
        }
        return -1;
    }
};

int main()
{
    vector<vector<char>> v{ {'+','+','.','+'},{'.','.','.','+'},
        {'+','+','+','.'} };
    vector<int> t{ 1, 2 };
    cout << Solution().nearestExit(v, t) << endl;

    return 0;
}